package com.yg.ssm.index.ctrl;

import com.yg.ssm.index.model.SysUserModel;
import com.yg.ssm.index.serv.LoginService;
import com.yg.ssm.util.DateUtil;
import com.yg.ssm.util.RepModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/8/26.
 */
@Controller
public class IndexCtroller {


    @Autowired
    private LoginService loginService;

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping("/")
    public String index(@RequestParam(name = "msg", defaultValue = "") String msg, Model model, HttpServletRequest req) {
        String message = (String) req.getAttribute("msg");
        if (!"".equals(message) && "authValid".equals(message)) {
            model.addAttribute("msg", "用户权限超时，请重新登录！");
        }
        return "index";
    }

    @RequestMapping("/admin/main")
    public String goLogin(Model model, HttpServletRequest req, HttpServletResponse rep, @CookieValue("sid") String sid) {
        Object obj = req.getSession().getAttribute(sid);
        if (obj == null) {
            return "index";
        }
        System.out.println(obj);
        return "main";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public RepModel login(String username, String password, Model mo, HttpServletRequest req, HttpServletResponse rep) {
        System.out.println(username + ":" + password);
        RepModel rm = new RepModel();
        //接收用户名 密码
        SysUserModel um = loginService.queryUserModel(username);
        //根据用户名 查询用户信息
        if (null == um) {
            //用户不存在，查询出结果为空
            rm.setSuccess(false);
            rm.setMessage("用户名或密码不正确！");
            return rm;
        }
        //比较用户密码
        if (!um.getPassword().equals(password)) {
            //密码不致
            rm.setSuccess(false);
            rm.setMessage("用户名或密码不正确！");
            return rm;
        }
        //密码一致记录Session
        String sid = req.getSession().getId();
        req.getSession().setAttribute(sid, um);
        req.getSession().setAttribute(sid + um.getUid(), DateUtil.GetCurrentTime());
        //返回Cookie
        Cookie co = new Cookie("sid", sid);
        rep.addCookie(co);
        //更新用户最合登录时间
        um.setLast_login_time(DateUtil.GetCurrentTime());
        loginService.upUserLoginTime(um);
        rm.setSuccess(true);
        rm.setMessage("登录成功！");
        return rm;
    }
}
